package com.zh.work.service.platform.merch.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zh.work.dao.platform.merch.MerchInfoMapper;
import com.zh.work.entity.MerchantRecordEntity;
import com.zh.work.entity.merch.MerchInfoEntity;
import com.zh.work.entity.merch.QrCodeMerchFee;
import com.zh.work.service.platform.merch.MerchInfoService;
import com.zh.work.util.plateform.ServiceUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @Description: 商户信息设置业务逻辑实现层
 * @Author: Li.HuiNeng
 * @Create in: 2019/11/14
 * @Version: 1.0.1
 */
@Service
public class MerchInfoServiceImpl extends ServiceImpl<MerchInfoMapper, MerchInfoEntity> implements MerchInfoService {

    @Autowired
    private MerchInfoMapper merchInfoMapper;

    @Qualifier("taskExecutor")
    @Autowired
    private TaskExecutor taskExecutor;

    @Override
    public IPage<MerchInfoEntity> getMerchantPage(Page<MerchInfoEntity> page, MerchInfoEntity merchInfoEntity) {
        return this.merchInfoMapper.selectPage(page, new LambdaQueryWrapper<MerchInfoEntity>()
                // 商户类别(是否为沉默商户)
                .eq(StringUtils.isNotEmpty(merchInfoEntity.getSilenceMerch()), MerchInfoEntity::getSilenceMerch, merchInfoEntity.getSilenceMerch())
                // 商户编号
                .like(StringUtils.isNotEmpty(merchInfoEntity.getMerchNo()), MerchInfoEntity::getMerchNo, merchInfoEntity.getMerchNo())
                // 商户简称
                .like(StringUtils.isNotEmpty(merchInfoEntity.getMerchName()), MerchInfoEntity::getMerchName, merchInfoEntity.getMerchName())
                // 商户类型
                .eq(Objects.nonNull(merchInfoEntity.getMerchType()), MerchInfoEntity::getMerchType, merchInfoEntity.getMerchType())
                // 商户状态
                .eq(Objects.nonNull(merchInfoEntity.getStatus()), MerchInfoEntity::getStatus, merchInfoEntity.getStatus())
                // 商户联系人
                .like(StringUtils.isNotEmpty(merchInfoEntity.getLinkMan()), MerchInfoEntity::getLinkMan, merchInfoEntity.getLinkMan())
                // 终审状态
                .eq(Objects.nonNull(merchInfoEntity.getJudgStatus()), MerchInfoEntity::getJudgStatus, merchInfoEntity.getJudgStatus())
                // 审核状态
                .eq(Objects.nonNull(merchInfoEntity.getAuditStatus()), MerchInfoEntity::getAuditStatus, merchInfoEntity.getAuditStatus())
                // 审核代理商号
                .like(StringUtils.isNotEmpty(merchInfoEntity.getAuditAgentNo()), MerchInfoEntity::getAuditAgentNo, merchInfoEntity.getAuditAgentNo())
                // 手机号码
                .like(StringUtils.isNotEmpty(merchInfoEntity.getMobile()), MerchInfoEntity::getMobile, merchInfoEntity.getMobile())
                // 商户级别
                .eq(Objects.nonNull(merchInfoEntity.getMerchLevel()), MerchInfoEntity::getMerchLevel, merchInfoEntity.getMerchLevel())
                // 所属机构
                .like(StringUtils.isNotEmpty(merchInfoEntity.getBranchNo()), MerchInfoEntity::getBranchNo, merchInfoEntity.getBranchNo())
                // 操作时间
                .between(ObjectUtils.allNotNull(merchInfoEntity.getAddStartTime(), merchInfoEntity.getAddEndTime()),
                        MerchInfoEntity::getAddTime, merchInfoEntity.getAddStartTime(), merchInfoEntity.getAddEndTime())
                // 开通时间
                .between(ObjectUtils.allNotNull(merchInfoEntity.getStartDateTime(), merchInfoEntity.getEndDateTime()),
                        MerchInfoEntity::getOpenTime, merchInfoEntity.getStartDateTime(), merchInfoEntity.getEndDateTime())
        );
    }

    @Override
    public IPage<MerchInfoEntity> getMerchantAssigePage(Page<MerchInfoEntity> page, MerchInfoEntity merchInfoEntity) {
        return this.merchInfoMapper.selectPage(page, new LambdaQueryWrapper<MerchInfoEntity>()
                .select(MerchInfoEntity::getMerchName, MerchInfoEntity::getMerchNo));
    }

    @Override
    public List<QrCodeMerchFee> getMerchantQrCodeFee(String merchantNo) {
        return this.merchInfoMapper.getMerchantQrCodeFee(merchantNo);
    }

    @Override
    public int putMerchantInfo(MerchInfoEntity merchInfoEntity) throws RuntimeException {
        // 添加商户二维码费率信息
        List<QrCodeMerchFee> qrList = JSON.parseArray(merchInfoEntity.getQrCodeRateJson(), QrCodeMerchFee.class);
        if (Objects.isNull(merchInfoEntity.getBranchNo())) return -1;
        if (Objects.isNull(merchInfoEntity.getSuperAgent())) {
            merchInfoEntity.setSuperAgent(merchInfoEntity.getBranchNo());
        }
        // 构造商户编号
        String merchantNo = ServiceUtil.creatMerchantNo(merchInfoEntity.getBranchNo(), merchInfoEntity.getProvinceCity(), merchInfoEntity.getMcc());
        try {
            if (qrList != null){
                if (qrList.size() > 0) {
                    qrList.forEach(f -> {
                        f.setMerchNo(merchantNo);
                        f.setAgentNo(merchInfoEntity.getBranchNo());
                        f.setBranchNo(merchInfoEntity.getBranchNo());
                    });
                    int i = this.merchInfoMapper.addBatchMerchantFee(qrList);
                    if (i <= 0) return -3;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("批量加入商户二维码费率出错!");
        }
        /** 设置图片 */
        ServiceUtil.setImageInfo(null, merchInfoEntity);
        /** 开始新增商户信息 */
        merchInfoEntity.setMerchNo(merchantNo);
        if (!merchInfoEntity.insert()) return -4;
        return 1;
    }

    @Override
    public int modMerchantInfoById(MerchInfoEntity merchInfoEntity) throws Exception {
        // 添加商户二维码费率信息
        try {
            List<QrCodeMerchFee> qrList = JSON.parseArray(merchInfoEntity.getQrCodeRateJson(), QrCodeMerchFee.class);
            Map<String, Long> map = merchInfoMapper.getMerchantFeeNum(merchInfoEntity.getMerchNo());
            if (map.get("num") != 0) {
                // 删除之前的二维码费率
                this.merchInfoMapper.delQrCodeFee(merchInfoEntity.getMerchNo());
            }
            if (qrList.size() > 0) {
                qrList.forEach(f -> {
                    f.setMerchNo(merchInfoEntity.getMerchNo());
                    f.setAgentNo(merchInfoEntity.getSuperAgent());
                    f.setBranchNo(merchInfoEntity.getBranchNo());
                });
                // 然后再添加新的二维码费率
                this.merchInfoMapper.addBatchMerchantFee(qrList);
            }
            // 修改商户信息本身
            this.merchInfoMapper.updateById(merchInfoEntity);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
        return 1;
    }

    @Override
    public int putMerchantAudit(MerchInfoEntity merchInfoEntity) {
        if (Objects.nonNull(merchInfoEntity.getAuditStatus())) {
            merchInfoEntity.setAuditTime(new Date());
        } else
            merchInfoEntity.setJudgAuditTime(new Date());
        return merchInfoMapper.putMerchantAudit(merchInfoEntity);
    }

/*    @Override
    public List<AgentInfoEntity> getMerchParentAgent(MerchInfoEntity merchInfoEntity) {
        this.merchInfoMapper.selectList(new LambdaQueryWrapper<MerchInfoEntity>());
        return null;
    }*/


    @Override
    public int addMerchantRecord(MerchantRecordEntity merchantRecordEntity) {
        return this.merchInfoMapper.addMerchantRecord(merchantRecordEntity);
    }

    @Override
    public List<MerchInfoEntity> getMerchListByAgentNo(String agentNo) {
        return this.merchInfoMapper.selectList(new LambdaQueryWrapper<MerchInfoEntity>()
        .select(MerchInfoEntity::getMerchName, MerchInfoEntity::getMerchNo)
        .eq(StringUtils.isNotEmpty(agentNo), MerchInfoEntity::getSuperAgent, agentNo));
    }

    @Override
    public Map<String, String> getMerchInfoByUserId(Long userId) { return merchInfoMapper.getMerchInfoByUserId(userId); }

    @Override
    public Map<String, String> getMerchantListIsNoByFegin(String merchantNo) {
        return merchInfoMapper.getMerchantListIsNoByFegin(merchantNo);
    }

    @Override
    public int updateMerchInfoScoreByMerchNo(String merchantNo,String score) {
        return merchInfoMapper.updateMerchInfoScoreByMerchNo(merchantNo,score);
    }

    @Override
    public int getMerchType(String merchantNo) {
        return merchInfoMapper.getMerchType(merchantNo);
    }
}
